//nodemon框架能自动重启服务器，运行代码：
//nodemon server.js

//1. 引入express
const express = require('express');
//2. 创建应用对象
const app = express();

//读写文件
let client1_acc = []
let client2_acc = []

const fs = require('fs');
const readline = require('readline');
let rl = readline.createInterface({
    input: fs.createReadStream(__dirname + '/server.log')
})
let cnt = 0  //记录当前行数
const interval = 200  //读取数据的间隔
const SES_a = 0.8  //指数平滑的系数

rl.on('line', line => {
    
    if(line[92] == '1'){
        if(cnt % interval == 0){
            if(client1_acc.length == 0) client1_acc.push(+line.slice(95, 99))
            else client1_acc.push( SES_a * client1_acc[client1_acc.length-1] + (1-SES_a)*(+line.slice(95, 99)))  //一次指数平滑
        }   
    }
    else{
        if(cnt % interval == 0){
            if(client2_acc.length == 0) client2_acc.push(+line.slice(95, 99))
            else client2_acc.push( SES_a * client2_acc[client2_acc.length-1] + (1-SES_a)*(+line.slice(95, 99)))  //一次指数平滑
        }  
    }

    cnt = (cnt+1) % interval
    
})


//3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装 

//axios 服务
app.all('/axios-client1', (request, response) => {
    //设置响应头  设置允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*');  //允许跨域
    response.setHeader('Access-Control-Allow-Headers', '*');  //允许自定义请求头
    response.send(JSON.stringify(client1_acc));
});

app.all('/axios-client2', (request, response) => {
    //设置响应头  设置允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*');  //允许跨域
    response.setHeader('Access-Control-Allow-Headers', '*');  //允许自定义请求头
    response.send(JSON.stringify(client2_acc));
});


//4. 监听端口启动服务
app.listen(8000, () => {
    console.log("服务已经启动, 8000 端口监听中....");
    console.log('http://127.0.0.1:8000/')
});


console.log('看啊可能')